package ca.llsutherland.nfl.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import ca.llsutherland.nfl.domain.Conference;
import ca.llsutherland.nfl.exception.ValidationException;
import ca.llsutherland.nfl.helper.ConferenceHelper;
import ca.llsutherland.nfl.util.StringUtil;

public class ConferenceDao extends BaseDao {

	private static ConferenceDao instance = new ConferenceDao();
	
	@Override
	public String getUnderlyingTableName() {
		return "CONFERENCE";
	}

	public static ConferenceDao getInstance(){
		return instance;
	}
	
	public Conference findByName(String name) {
        String findByNameQuery = getFindByNameQuery(name);
        return buildConference(findByNameQuery);
    }
	
	private Conference buildConference(String sql) {
		Conference conference = null;
        ResultSet rs = super.findByQuery(sql);
        
        try {
            if(rs.next()){
            	conference = ConferenceHelper.createNewConference(Long.valueOf(rs.getLong("ID")), rs.getString("NAME"));
            }
            rs.close();
        } catch (SQLException e) {
            throw new ValidationException(e.getMessage() + " in buildConference()");
        } finally {
            rs = null;            
        }
        return conference;
    }

	public Conference create(Conference conference) {
		String sql = "INSERT INTO " + getUnderlyingTableName() + " (NAME) VALUES (" + StringUtil.addSingleQuotes(conference.getName()) + ");";
        return findById(super.create(sql));
	}
	
	public Conference findById(Long id) {
        String findByIdQuery = getFindByIdQuery(id);
        return buildConference(findByIdQuery);
    }
}
